package com.xq.shop.aop;

import com.xq.shop.config.Redis;
import com.xq.shop.dao.domain.entity.LoginLog;
import com.xq.shop.dto.LoginDto;
import com.xq.shop.service.ILoginLogService;
import com.xq.shop.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import utils.BaseConstants;
import utils.BaseResult;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author gaoxiaojin
 */
@Aspect
@Component
@Slf4j
public class LoginAspect {

    @Resource
    private ILoginLogService loginLogService;
    @Resource
    private Redis redis;

    @Pointcut("execution(* com.xq.shop.controller.UserController.login(..))")
    public void loginSuccessPointCut(){}

    @AfterReturning(pointcut="loginSuccessPointCut()", returning = "result")
    public void loginSuccess(JoinPoint joinPoint, BaseResult<String> result) throws Exception {
        log.info("记录登录日志--start");
        String token = redis.existsLike(result.getData(), 0);
        UserVo userVo = (UserVo) redis.get(token);
        //添加登录日志
        Object[] args = joinPoint.getArgs();
        LoginDto dto = (LoginDto) args[0];
        LoginLog loginLog = new LoginLog();
        loginLog.setSystemBrowserInfo();
        if (Objects.isNull(dto.getIp()) || BaseConstants.DEFAULT_IP.equals(dto.getIp())) {
            loginLog.setIp("-");
            loginLog.setArea("-");
        } else {
            loginLog.setIp(dto.getIp());
            loginLog.setAddressInfo();
        }
        loginLog.setUserId(userVo.getId());
        loginLog.setUsername(userVo.getUsername());
        loginLogService.save(loginLog);
        log.info("登录日志信息：{}", loginLog);
        log.info("记录登录日志--end");
    }

}
